﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;

/**
 * Copyright 2011 by Alberto Gemin
 * agemin@hotmail.com
 * Version 1.2.0.1
 * 19 Dec 2011
 **/
namespace Gemina.CRM2011.WF.CrmDistributeWF
{
    [AgCodeActivity("Distribute One to Many", "DWF AG Utilities")]
    public sealed class DistributeWFActivityOnetoMany : DistributeWFActivity
    {

        override protected List<Guid> GatherKeys(CodeActivityContext executionContext)
        {
            OneToManyRelationshipMetadata relationship = this.GetRelationship(executionContext);

            QueryByAttribute query = new QueryByAttribute();
            query.EntityName = relationship.ReferencingEntity;
            query.Attributes.Add(relationship.ReferencingAttribute);
            query.Values.Add(this.CurrentRecordId.ToString());

            RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();
            retrieveRequest.Query = query;

            // Foreach object just get the primary key
            List<Guid> keyList = new List<Guid>();
            RetrieveMultipleResponse retrieveResponse = (RetrieveMultipleResponse)this.GetService(executionContext).Execute(retrieveRequest);
            foreach (Entity entity in retrieveResponse.EntityCollection.Entities)
            {
                keyList.Add(entity.Id);
            }

            return keyList;
        }

        private OneToManyRelationshipMetadata GetRelationship(CodeActivityContext executionContext)
        {
            RetrieveRelationshipRequest relationshipRequest = new RetrieveRelationshipRequest();
            relationshipRequest.Name = this.RelationshipName.Get(executionContext);
            relationshipRequest.RetrieveAsIfPublished = false;

            RetrieveRelationshipResponse relationshipResponse = (RetrieveRelationshipResponse)this.GetService(executionContext).Execute(relationshipRequest);
            if (!(relationshipResponse.RelationshipMetadata is OneToManyRelationshipMetadata))
            {
                throw new AgErrorMessage("Relationship is not One to Many");
            }
            OneToManyRelationshipMetadata rel = (OneToManyRelationshipMetadata)relationshipResponse.RelationshipMetadata;
            return rel;
        }

    }
}
